const Koa = require('koa')
const path = require('path')
const parseError = require('parse-error')
const {Nuxt, Builder} = require('nuxt')
//const bodyParser = require('koa-bodyparser')
const bodyParser = require('koa-body')
const apiroutes = require('./routes/index')
const apiResponseFormatter = require('./middleware/response_formatter')
const checkapi404 = require('./middleware/checkapi404')
const {apiPrefix} = require('./config')
require('./dbhelper/db')
const tokenHelper = require('./util/token-helper')
const sslify = require('koa-sslify').default
const https = require('https')
const http = require('http');
const fs = require('fs')
const httpProxy = require('http-proxy-middleware');
const {createProxyMiddleware} = require('http-proxy-middleware');
const k2c = require('koa2-connect');
const GuacamoleLite = require('guacamole-lite');
const scheduleTools = require('./util/scheduleTools')


const app = new Koa()


const config = require('../nuxt.config.js')
config.dev = app.env !== 'production'


// // /* 代理配置 start */
// const proxy = require('koa2-proxy-middleware'); //引入代理模块
// const options = {
//     targets: {
//         // (.*) means anything
//         '/fb/(.*)': {
//             target: 'http://127.0.0.1:8080/fb',
//             changeOrigin: true,
//            pathRewrite: {'^/fb': '/'}
//         },
//     }
// }
// app.use(
//     proxy(options)
// );
//设置远程服务guacd配置
const guacdOptions = {
  port: 4822 // port of guacd
};
const clientOptions = {
  crypt: {
    cypher: 'AES-256-CBC',
    key: 'MySuperSecretKeyForParamsToken12'
  },
  log: {
      level: 'DEBUG'
  }
};


//设置文件服务器
app.use(async (ctx, next) => {
  if (ctx.url.startsWith('/fb/share/') || ctx.url.startsWith('/fb/api/public/share') || ctx.url.startsWith('/fb/static/')) {
    await k2c(createProxyMiddleware({
        target: 'http://127.0.0.1:8080/fb',
        changeOrigin: true,
        secure: false,
        pathRewrite: {
          '^/fb': '/'
        }
      }
    ))(ctx, next);
  } else if (ctx.url.startsWith('/fb')) { //匹配有api字段的请求url
    if (!ctx.header.cookie) {
      console.log('url：', ctx.url, ctx.request.method, "没有cookie")
      await next
    } else if (ctx.header.cookie.includes("user=")) {
      console.log('url：', ctx.url, ctx.request.method, "有cookie有user")
      //ctx.respond = false // 绕过koa内置对象response ，写入原始res对象，而不是koa处理过的response

      await k2c(httpProxy.createProxyMiddleware({
          target: 'http://127.0.0.1:8080/fb/',
          changeOrigin: true,
          secure: false,
          pathRewrite: {
            '^/fb': '/'
          }
        }
      ))(ctx, next);

    }

  } else {
    await next()
  }
  //
})


// 进行requestbody解析
app.use(bodyParser(
  {
    multipart: true,
    formidable: {
      //上传文件存储目录
      //uploadDir:  path.join(__dirname, '~/assets/uploads/'),
      //maxFileSize: 200*1024*1024 ,   // 设置上传文件大小最大限制，默认2M
      //允许保留后缀名
      keepExtensions: true,
      multipart: true,
    }
  }
));

// app.use(async (ctx, next)=>{
//     try{
//         await next();   // 执行后代的代码
//         if(!ctx.body){  // 没有资源
//             ctx.status = 404;
//             ctx.body = "not found"
//           console.log("最外层看到404了")
//         }
//     }catch(e){
//         // 如果后面的代码报错 返回500
//        console.log("最外层看到500了")
//         ctx.status = 500;
//         ctx.body = "server error"
//     }
// })

//加入api路由
app.use(apiResponseFormatter(apiPrefix));//格式化api返回数据
//检查token同时定义一些不需要检查的路由
app.use(tokenHelper.checkToken(apiPrefix, [
  '/api/user/signup',
  '/api/login'
], ['/api/urllist']));
app.use(apiroutes.routes(), apiroutes.allowedMethods());//加载api路由
app.use(checkapi404(apiPrefix));


async function start() {
  // Instantiate nuxt.js
  const nuxt = new Nuxt(config)

  const {
    host = process.env.HOST || '127.0.0.1',
    //host = '0.0.0.0' || '127.0.0.1',
    port = process.env.PORT || 3000
  } = nuxt.options.server

  await nuxt.ready()
  // Build in development
  if (config.dev) {
    const builder = new Builder(nuxt)
    await builder.build()
  }

  app.use((ctx) => {
    ctx.status = 200
    ctx.respond = false // Bypass Koa's built-in response handling
    ctx.req.ctx = ctx // This might be useful later on, e.g. in nuxtServerInit or with nuxt-stash
    nuxt.render(ctx.req, ctx.res)
  })
  // app.listen(port, host)
  // consola.ready({
  //   message: `Server listening on http://${host}:${port}`,
  //   badge: true
  // })


//   const privateKey = fs.readFileSync(path.resolve(__dirname, 'cert.key'), 'utf8');
//   const certificate = fs.readFileSync(path.resolve(__dirname, 'cert.crt'), 'utf8');
//   const credentials = {
//     key: privateKey,
//     cert: certificate,
// // ca: ca
//   };
//   const httpServer = https.createServer(credentials, app)
//   httpServer.listen(port, host);
  //http server


// app.use(sslify())  // 使用ssl
//  const server = https.createServer(nuxt.options.server.https, app.callback())

  const server = https.createServer(nuxt.options.server.https, app.callback())
  const guacServer = new GuacamoleLite({server}, guacdOptions, clientOptions);
  guacServer.on('error', (clientConnection, error) => {
    console.error(clientConnection, error);
  });
  server.listen(443, host, () => {
  });
  consola.ready({
    message: `Server listening on https://${host}`,
    badge: true
  })
// const app2 = new Koa()
// const server = https.createServer(nuxt.options.server.https,app2.callback());
// const guacServer = new GuacamoleLite({server}, guacdOptions, clientOptions);
// server.listen(9090);

}

start()
//检查开机ARP扫描任务
scheduleTools.appStartCheckJob()
